<template>
  <view class="page">
    <!-- 头部 start -->
    <view class="cu-custom bg-white" :style="[{height: CustomBar+'px'}]">
    	<view class="cu-bar bg-white  fixed" :style="[{ height: CustomBar + 'px', paddingTop: StatusBar + 'px' }]" >
    		<view class="action"   @tap="back(1)">
    			<text class="cuIcon-back "></text>
    		</view>
    		<view class="content "  :style="[{top:StatusBar + 'px'}]">
          {{i18n['选择自取点']}}
    		</view>
        <view class="right padding-right text-white" >
        </view>
    	</view>
    </view>
    <!-- 头部 end -->
    <!-- 筛选 -->
    <view class="solid-top solid-bottom padding-tb-xs">
      <view class="cu-custom bg-white "  style="height:80rpx;margin:10rpx 24rpx;">
        <view class="cu-bar   flex justify-around search-wrap" >
          <view class="search-form round" >
            <text class="cuIcon-search" ></text>
            <input confirm-type="search"  type="text" v-model="keywords" :adjust-position="false" :hold-keyboard="false" :placeholder="placeholder" @confirm="searchConfirm" />
            <text v-if="keywords.length != 0" class="cuIcon-close text-gray padding-right-xs" @tap="handleClear"></text>
          </view>
          <view @click="searchConfirm(1)" class="padding-right-sm" style="border-left:3rpx dashed #c5c7cf;padding-left: 30rpx;" > {{i18n['搜索']}}</view>
        </view>
      </view>
    </view>

    <!-- 筛选 结束-->
    <view class="pos flex justify-between " style="margin:30rpx  24rpx;">
      <view class="flex align-center _l text-lg">
        <text class="cuIcon-location text-xl text-999"></text>
        <text class="text-cut">
          <block class="" v-if="location.district != ''">{{location.district || ''}}</block>
          <block  v-if="selectItem.deliver_name ">{{selectItem.deliver_name}}</block>
          <block  v-else> {{i18n['请选择自取点']}}</block>
        </text>
      </view>
      <view class="_r flex align-center text-gray"	@click="getLocation">
        <text class="cuIcon-locationfill text-xl"></text>
        <text class="text-df">{{i18n['重新定位']}}</text>
      </view>

    </view>
    <view class="bg">

    </view>
    <view class="location-title padding-lr padding-tb-sm text-lg text-999 solid-bottom">
       {{i18n['商品自取点']}}
    </view>
    <!-- 内容选择 -->
  <view v-if="lists.length > 0 "  class="margin-top-sm" :style="{maxHeight: 'calc(100% - '+(CustomBar + 200)+'px)'}" style=" margin:0 24rpx 20rpx 24rpx;border-radius: 20rpx;  overflow: hidden;"  >
    <scroll-view   style="  height: 100%; " scroll-y>
        <block v-for="(item, index) in lists" :key="item.id">
          <view >
            <view class="flex justify-between solid-bottom padding-tb-sm" >
               <!-- <view class="icon_left">
                 <image class="img"  :src="item.thumb" mode="aspectFill" ></image>
               </view> -->
               <view  class="pos-content">
                  <view class="address_detail">{{item.full_address}}</view>
                  <!-- <view class="margin-top-sm text-999"> {{item.deliver_name}}</view> -->
									<view class="margin-top-sm">{{item.deliver_mobile}}<text class="margin-left text-theme" @tap="copyInfo(item.deliver_mobile)">复制</text></view>
               </view>
               <view class="icon_left_select text-center text-white text-df margin-left-sm round" @click="back(item)">
                   {{i18n['选择']}}
               </view>
            </view>
          </view>
        </block>
    </scroll-view>
  </view>

   <!-- 操作按钮 start -->
  <!-- <view class="bottom-action">
     <view class="btn2" @click="back">提交选择</view>
   </view> -->
   <!-- 操作按钮 end -->
   <fu-loading v-if="isShowLoading"></fu-loading>
  <!--商品列表 end-->
  <!-- 空布局 -->
  <fu-empty-ui v-if="lists.length == 0 && isInit"></fu-empty-ui>
  <!-- 加载状态 -->
  <!-- 断网检测组件 -->
  <fu-notwork></fu-notwork>
  </view>
</template>
<script>
  // 高德地图sdk
  import amapFile from '@/libs/amap-wx.js';
  export default {
    data() {
      return {
        myAmapFun: null, // 高德地图实例
        province: '', // 省
        city: '', //市
        district: '', //区
        provinceCode: '', // 省 code码
        cityCode: '', //市 code码
        districtCode: '', //区 code码
        addressDesc: '', // 详细地址
        latitude:'',
        longitude:'',

        selectItem:{},
        currentSelect:null,
        isShowLoading: true, // 是否显示loading
        keywords: '', // 搜索的文本
        placeholder: global.i18n['输入地址，查找附近自提点'] , // 默认文本
        lists: [], // 结果列表
        cid: '', // 分类id(点击分类跳转过来必传)
        isInit: false, // 是否请求过数据
        district:{},//区id
        location:{},//省市区
      };
    },

    onLoad(options) {
      // 初始化高德地图SDK,记得换成自己的key
      let location = this.$store.state.location;
      this.myAmapFun = new amapFile.AMapWX({ key: '71e2d1e8fad67225279e724ff7c51e64' });
      // 定位功能
      if(!location  ||  !location.district){
        // 初始化高德地图SDK,记得换成自己的key

        this.autoGetLocation();
      }else{
        this.location = location;
        this.handleSearch()
      }



      // console.log(options, '参数');
      // const { type = '', id = '' ,name = '' } = options;
      // if(type == 1){
      //   this.district={
      //     id:id,
      //     name:name,
      //   }
      //   this.handleSearch()
      // } else {
      //     this.loadDataOptions(); // 搜索方法
      // }






    },
    methods: {
      /**
       * @func 定位地址
       */
      getLocation() {
      	let _this = this;
      	//#ifdef MP-WEIXIN
      	uni.getSetting({
      		success(res) {
      			// 获取设置成功
      			console.log(res.authSetting);
      			if (!res.authSetting['scope.userLocation']) {
      				// 如果没开启权限提示打开
      				uni.openSetting({
      					success(res) {
      						// 打开成功，提示获取权限
      						console.log(res.authSetting);
      						uni.authorize({
      							scope: 'scope.userLocation',
      							success(res) {
      								_this.chooseLocation();
      							},
      							fail(res) {
      								console.log(res);
      								this.$message.info( this.i18n['打开权限失败']);
      							}
      						});
      					}
      				});
      			} else {
      				_this.chooseLocation();
      			}
      		}
      	});
      	//#endif
      	this.chooseLocation();
      },
      /**
       * @func 地图选点
       */
      chooseLocation() {
        let _this = this;
      	uni.chooseLocation({
      		success: (res) => {
      			console.log(res, '地图');
      			this.myAmapFun.getRegeo({
      				location: res.longitude + ',' + res.latitude,
      				success: (data) => {
      					//成功回调
      					console.log('自动定位 SDK回调', data);
      		    					let regeoData = data[0].regeocodeData.addressComponent;
      		    					this.province = regeoData.province;
      		    					this.city = Array.isArray(regeoData.city) && (regeoData.city.length == 0) ? regeoData.province: regeoData.city;
      		    					this.district = regeoData.district;
      		    					this.addressDesc = data[0].desc;
      		    					this.provinceCode = regeoData.adcode.substr(0,2)+'0000';
      		    					this.cityCode = regeoData.adcode.substr(0,4)+'00';
      		    					this.districtCode = regeoData.adcode+'';
      		              let latitude= data[0].latitude
      		              let longitude= data[0].longitude

      		              _this.$store.commit('updataLocation', {
      		                province: this.province,
      		                city: this.city,
      		                district:this.district,
      		                addressDesc: this.addressDesc,
      		                provinceCode: this.provinceCode,
      		                cityCode: this.cityCode,
      		                districtCode: this.districtCode,
      		                latitude:latitude,
      		                longitude:longitude,

      		              });
      		              _this.location= {
      		                province: this.province,
      		                city: this.city,
      		                district:this.district,
      		                addressDesc: this.addressDesc,
      		                provinceCode: this.provinceCode,
      		                cityCode: this.cityCode,
      		                districtCode: this.districtCode,
      		                latitude:latitude,
      		                longitude:longitude,
      		              }
                this.handleSearch()
      				},
      				fail: (info) => {
                this.loadDataOptions(); // 搜索方法
      					//失败回调
      					console.log(info)
      				}
      			})
      		}
      	})
      },
      /**
       * @func 自动定位
       */
      autoGetLocation() {
        let _this = this;
      	console.log("自动定位");
      	uni.getLocation({
      		geocode: true,
      		success: (adr) => {
      			this.myAmapFun.getRegeo({
      				location: adr.longitude + ',' + adr.latitude,
      				success: (data) => {
      					//成功回调
      					console.log('自动定位 SDK回调', data);
      					let regeoData = data[0].regeocodeData.addressComponent;
      					this.province = regeoData.province;
      					this.city = Array.isArray(regeoData.city) && (regeoData.city.length == 0) ? regeoData.province: regeoData.city;
      					this.district = regeoData.district;
      					this.addressDesc = data[0].desc;
      					this.provinceCode = regeoData.adcode.substr(0,2)+'0000';
      					this.cityCode = regeoData.adcode.substr(0,4)+'00';
      					this.districtCode = regeoData.adcode+'';
                this.latitude= data[0].latitude
                this.longitude= data[0].longitude
                _this.$store.commit('updataLocation', {
                  province: this.province,
                  city: this.city,
                  district:this.district,
                  addressDesc: this.addressDesc,
                  provinceCode: this.provinceCode,
                  cityCode: this.cityCode,
                  districtCode: this.districtCode,
                  latitude:this.latitude,
                  longitude:this.longitude,
                });
                _this.location= {
                  province: this.province,
                  city: this.city,
                  district:this.district,
                  addressDesc: this.addressDesc,
                  provinceCode: this.provinceCode,
                  cityCode: this.cityCode,
                  districtCode: this.districtCode,
                  latitude:this.latitude,
                  longitude:this.longitude,
                }
                this.handleSearch()
      				},
      				fail: (info) => {
      					//失败回调
      					console.log(info)
      				}
      			})

      		}
      	})
      },
      //获取左边的内容
      // loadDataOptions() {
      //   this.$api.post(global.apiUrls.getInviteCitys)
      //     .then(res => {
      //       if (res.data.code == 1) {
      //         let list = res.data.data;
      //         console.log('分类数据', list)
      //         if(list &&  list.length > 0){
      //           this.district = list[0]
      //           this.handleSearch()
      //         }
      //       } else {
      //         this.isShowLoading = false
      //         this.isInit = true
      //         this.$message.error(res.data.msg);
      //       }
      //     })
      // },

      /**
       * @description 获取分类数据
       */
      loadDataOptions() {
        const that = this
        this.$api.post(global.apiUrls.getInviteCitys,{
          code:this.location.cityCode || ''
        })
          .then(res => {
            if (res.data.code == 1) {
              let list = res.data.data;
              console.log('分类数据', list,that.location)
              this.lists = list;
              if(that.lists.length >0 && that.location && that.location.districtCode ){
                    that.lists.forEach(function(item,index){
                      if(item.region_code == that.location.districtCode){
                            this.district = item
                            that.handleSelect(item,index)
                       }
                  })
               }
               if(this.lists.length > 0 && !that.location ){
                 this.district = that.lists[0]
               }

              //	默认显示推荐数据
            } else {

              this.isShowLoading = false
              this.isInit = true
              this.$message.error(res.data.msg);
            }
          })
      },

      handleSearch() {
        this.isShowLoading = true
        this.isInit = false
        this.$api.post(global.apiUrls.getInviteAddress, {
            district_id: this.district.id || 0,
            deliver_name:this.keywords,
            region_code: this.location.districtCode,
            longitude:this.location.longitude,
            latitude:this.location.latitude
          })
          .then(res => {
            this.currentSelect = null
            this.isShowLoading = false
            this.isInit = true
             this.lists=[]
            if (res.data.code == 1) {
              this.lists = res.data.data && res.data.data.data || []
              console.log('自取点', res)
            } else {
              this.isShowLoading = false
              this.isInit = true
              this.$message.error(res.data.msg);
            }
          })

      },

	/**
			 * @description 切换选中
			 * @param {Object} item 选中数据
			 * @param {Number} idx 选中下标
			 */
			choose(item, idx) {
	      this.selectItem = item
        this.currentSelect = idx

			},
      changeDistrict(){
        this.$urouter.redirectTo({
          url: '/pages/index/select-location/select-location/index',
          params: {
            type: 1
          }
        });

      },


      /**
       * @event
       * @description 去商品详情
       */
      navToDetail(item) {
        this.$urouter.navigateTo({
          url: '/pages/goods/goodsdetail/goods-detail/index',
          params: {
            sku_id: item.sku_id || 0,
            goods_id: item.id
          }
        });
      },


      /**
       * @description 切换搜索条件
       * @param {Object} e input框事件源
       */
      searchConfirm(e) {
        if(e == 1 && this.keywords.trim() == ''){
          this.$message.info(this.i18n['请输入要搜索的内容']);
          return;
        }
        if (e && e!==1 &&  e.detail.value.trim() == '') {
          this.$message.info(this.i18n['请输入要搜索的内容'] );
          return;
        }
        this.handleSearch();
        uni.hideKeyboard();
      },

      // 清除关键字
      handleClear() {
        this.keywords = '';
        this.handleSearch();
        uni.hideKeyboard();
      },
      // 返回
      back(value) {
        if(value == 1){
           uni.navigateBack();
           return
        }
        console.log(this.district,7777)
        // if(!this.selectItem ||  !this.selectItem.deliver_name){
        //     this.$message.info('请选择自取点');
        //     return
        // }
        this.selectItem = value;
        this.selectItem.district_id = this.district.id
        this.selectItem.district_name = this.district.name

        uni.$emit("select_take_address", this.selectItem);
        uni.navigateBack();


      },
			/**
			 * @description copy复制
			 * @param {String} data 数据
			 */
			copyInfo(data) {
			  let that = this;
			  uni.setClipboardData({
			    data,
			    success: function () {
			      that.$message.info(this.i18n['复制成功']);
			      // console.log('success');
			    }
			  });
			},
    }
  };
</script>

<style lang="scss" scoped>
  .page {
    height:100vh;
    background: #ffffff;
  }
  .current_select{
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 400;
    padding-top: 4rpx;
  }

  .icon_left{
     height: 144rpx;
     width: 144rpx;
     overflow: hidden;
     flex-shrink: 0;
     // position: relative;
     // top:5rpx;
     image{
      height: 144rpx;
      width: 144rpx;
      border-radius: 8rpx;
     }
  }
  .pos-content{
    width: calc(100% - 164rpx);
  }
  .icon_left_select{
    height: 64rpx;
    width: 128rpx;
    line-height: 64rpx;
    background: $theme;
    // border-radius: 12rpx;
    align-self: center;

  }
  .search-wrap{
    height:80rpx;
    border-radius: 21rpx;
    padding-right:0;
    background: #F5F5F5;
  }
  .pos{
    ._l{
      width: calc(100% - 100rpx);
    }
    ._r{
      flex-shrink: 0;
    }
  }
  .location-title{

  }
  .bg{
    background: #F5F5F5;
    height: 20rpx;
  }
  .text-cut-1 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
  }
  .address_detail{
    // position: relative;
    // top:-40rpx;
    width: 100%;
  }

  .top_right{
    border:1rpx solid #A8A8A8;
    border-radius: 20rpx;
    padding:4rpx 18rpx;
    display: flex;
    align-items: center;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 400;
    color: #999999;
  }
 .icon {
 	display: block;
 	width: 20rpx;
 	height: 20rpx;
 	flex-shrink: 0;
 }
  .confirm-type {
    margin-right: 20rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 40rpx;
    background-color: #FFE26C;
    padding: 10rpx 25rpx;
    border-radius: 25rpx;
    color: #333333;
    opacity: 1;
  }


  .page_title {
    font-size: 30rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    // letter-spacing: 1rpx;

  }

  .bottom-action {
    position: fixed;
    right: 32rpx;
    left: 32rpx;
    bottom: 56rpx;
    bottom: calc(56rpx + constant(safe-area-inset-bottom));
    bottom: calc(56rpx + env(safe-area-inset-bottom));
    display: flex;

    view {
      height: 88rpx;
      flex: 1;
      line-height: 88rpx;
      text-align: center;
      border-radius: 88rpx;
      color: #FFFFFF;
    }

    .btn1 {
      margin-right: 32rpx;
      background: linear-gradient(126deg, #39b54a 0%, #8dc63f 100%);
    }

    .btn2 {
      background: linear-gradient(126deg, #FA2033 0%, #FF6530 100%);
    }
  }


</style>
